from ...libs.functions.common_ui_elements import collapsable, multiline_print


def soft_start_end(layout, toggles, active_group, emission_props) -> None:
    
    """ Esta sección esta tanto en Geometry como en Inflow """

    # Soft:
    soft_sect = collapsable(
        layout,
        toggles,
        "fs_emission_soft",
        "Soft",
        'FILE_VOLUME',
        align=True,
    )
    if soft_sect:

        ss_animed = active_group.get_soft_start_keyframes
        se_animed = active_group.get_soft_end_keyframes

        soft_start = soft_sect.column(align=True)
        soft_start_row = soft_start.row(align=True)
        soft_start_row.scale_y = 1.3

        if ss_animed:
            # para poner el boton como los otros porperty use splits:
            flow = soft_start_row.grid_flow(row_major=False, even_columns=False, even_rows=False, align=True, columns=2)
            flow.label(text="")
            bt_rm = flow.row(align=True)
            bt_rm.scale_x = 2.32
            bt_rm.alert = True
            bt_rm.operator("fluidlab.fs_emission_soft_start_remove", icon='KEY_DEHLT', text="Soft Start")
        else:
            soft_start_row.prop(emission_props, "soft_start", toggle=True, text="Soft Start")
        
        if emission_props.soft_start:

            # Si no está animado:
            if not ss_animed:
                soft_start_row.operator("fluidlab.fs_emission_soft_start_apply", text="Apply", icon='KEY_HLT')
                soft_start.prop(emission_props, "ss_frame_start", text="Frame Start")

                soft_start.prop(emission_props, "fluid_radius", text="Interaction Radius", slider=True)

            soft_start.use_property_split = True

        soft_sect.separator()

        soft_end = soft_sect.column(align=True)
        soft_end_row = soft_end.row(align=True)
        soft_end_row.scale_y = 1.3

        if se_animed:
            # para poner el boton como los otros porperty use splits:
            flow = soft_end_row.grid_flow(row_major=False, even_columns=False, even_rows=False, align=True, columns=2)
            flow.label(text="")
            bt_rm = flow.row(align=True)
            bt_rm.scale_x = 2.35
            bt_rm.alert = True
            bt_rm.operator("fluidlab.fs_emission_soft_end_remove", icon='KEY_DEHLT', text="Soft End")
        else:
            soft_end_row.prop(emission_props, "soft_end", toggle=True, text="Soft End")
        
        if emission_props.soft_end:
            # Si no está animado:
            if not se_animed:                    
                soft_end_row.operator("fluidlab.fs_emission_soft_end_apply", text="Apply", icon='KEY_HLT')
                sr_row = soft_end.row(align=True)
                sr_row.prop(emission_props, "se_frame_start", text="Start | Duration")
                sr_row.prop(emission_props, "se_duration", text="")
                soft_end.prop(emission_props, "se_amount", text="Amount")


# def unborn(layout, emission_props, emitter_ob):
    
#     # "Recomendamos"/Forzamos al usuario a usar el unborn solo si ya hizo bake:
#     psys = emitter_ob.particle_systems.active
#     if hasattr(psys, "point_cache"):
#         if not psys.point_cache.is_baked:
#             flow = layout.grid_flow(row_major=False, even_columns=False, even_rows=False, align=True, columns=2)
#             flow.label(text=" ")
#             feedback = flow.row(align=True)
#             feedback.scale_x = 1.46
#             text="To use the unborn option, it is recommended to bake first."
#             multiline_print(feedback, text, 7, 'INFO')
    
#     unborn = layout.row(align=True)
#     unborn.scale_y = 1.3
#     unborn.prop(emission_props, "show_unborn", text="Unborn", toggle=True)
#     if hasattr(psys, "point_cache"):
#         unborn.enabled = psys.point_cache.is_baked
#     else:
#         unborn.enabled = False


def emission_adv_ui(toggles, col, main_col, active_group, emitters_list, active_emitter_item, emission_props) -> None:
    
    # Si no hay emitters no mostramos emitters:
    if not emitters_list or not active_emitter_item:
        return
    
    if emitters_list.is_void:

        main_col.separator()
        title_list = active_group.emitter_type.title() + " Shapes List"
        main_col.box().label(text=title_list + " is void!", icon='INFO')
        
        return
    
    emitter_ob = next((ob for ob in active_emitter_item.group_coll.objects if ob.fluidlab.id_name == "Emitter_"+ active_emitter_item.id_name ), None)

    switchers_props = active_emitter_item.switchers

    # Emission:
    #----------
    # global_mode_emission_sect
    emisson_local_mode = {
            "type": "bool",
            "from": switchers_props,
            "prop": "global_mode_emission_sect",
            "text": "",
            "toggle": True,
            "icon": 'LINKED' if switchers_props.global_mode_emission_sect else 'UNLINKED',
            "emboss": False,
    }
    fs_emission_emission = collapsable(
        col,
        toggles,
        "fs_emission_emission",
        "Emission",
        'LIGHTPROBE_VOLUME',
        align=True,
        button_settings1=emisson_local_mode
    )
    if fs_emission_emission:
        
        if active_group and emitter_ob:

            fs_emission_emission.separator()

            if active_group.emitter_type == 'INFLOW' and emission_props.emit_from != 'VERT':

                c_or_r = fs_emission_emission.row(align=True)
                c_or_r.use_property_split = False
                c_or_r.scale_y = 1.3
                c_or_r.prop(emission_props, "count_or_resolution", expand=True)
                
                fs_emission_emission.separator()
                
            fs_emission_emission.prop(emission_props, "emit_from", text="Emit From")

            fs_emission_emission.separator()

            #------------------------------------------
            # Geometry
            #------------------------------------------
            if active_group.emitter_type == 'GEOMETRY':

                resolution = fs_emission_emission.row(align=True)
                if not active_emitter_item.gr_sz_toggle:
                    resolution.prop(emission_props, "grid_resolution", text="Resolution", slider=True)
                else:
                    resolution.prop(emission_props, "size", text="Size", slider=False) # el slider en true afecta a la sensibilidad de movimiento del ratón.
                
                resolution.prop(active_emitter_item, "gr_sz_toggle", text="", icon='MOD_LENGTH' if active_emitter_item.gr_sz_toggle else 'LIGHTPROBE_VOLUME', toggle=False)

                # fs_emission_emission.prop(emission_props, "grid_random", slider=True)
                fs_emission_emission.prop(emission_props, "size_random", text="Size Random", slider=True)


                fs_emission_emission.separator()

                f_start_end = fs_emission_emission.row(align=True)
                f_start_end.prop(emission_props, "frame_start", text="Frame Start | End")
                f_start_end.prop(emission_props, "frame_end", text="")

                fs_emission_emission.separator()
                
                fs_emission_emission.prop(emission_props, "lifetime", text="Lifetime")

                fs_emission_emission.prop(emission_props, "lifetime_random", text="Lifetime Randomness", slider=True)


                fs_emission_emission.separator()

                distribution = fs_emission_emission.row(align=True)
                distribution.scale_y = 1.3
                icon_dist = 'TRIA_DOWN'if emission_props.distribution_toggle else 'TRIA_LEFT'
                distribution.prop(emission_props, "distribution_toggle", toggle=True)
                distribution.prop(emission_props, "distribution_toggle", toggle=True, text="", icon=icon_dist)
                
                if emission_props.distribution_toggle:
                    # fs_emission_emission.separator()
                    fs_emission_emission.prop(emission_props, "use_modifier_stack", text="Use Modifier Stack")

                    fs_emission_emission.prop(emission_props, "show_unborn", text="Unborn")
                    fs_emission_emission.prop(emission_props, "grid_random", slider=True)
                
                # fs_emission_emission.separator()
                # unborn(fs_emission_emission, emission_props, emitter_ob)

                fs_emission_emission.separator()

                soft_start_end(col, toggles, active_group, emission_props)

            #------------------------------------------
            # InFlow
            #------------------------------------------
            elif active_group.emitter_type == 'INFLOW':
                
                count_size = fs_emission_emission.row(align=True)
                
                if emission_props.emit_from == 'VERT' or emission_props.count_or_resolution == 'COUNT':
                    count_size.prop(emission_props, "count", text="Count | Size")
                
                elif emission_props.count_or_resolution == 'RESOLUTION':
                    count_size.prop(emission_props, "inflow_resolution", text="Resolution | Size")


                count_size.prop(emission_props, "size", text="")
                fs_emission_emission.prop(emission_props, "size_random", text="Size Random", slider=True)

                fs_emission_emission.separator()

                f_start_end = fs_emission_emission.row(align=True)
                f_start_end.prop(emission_props, "frame_start", text="Frame Start | End")
                f_start_end.prop(emission_props, "frame_end", text="")

                fs_emission_emission.separator()

                fs_emission_emission.prop(emission_props, "lifetime", text="Lifetime")
                fs_emission_emission.prop(emission_props, "lifetime_random", text="Lifetime Random", slider=True)

                fs_emission_emission.separator()

                distribution = fs_emission_emission.row(align=True)
                distribution.scale_y = 1.3
                distribution.prop(emission_props, "distribution_toggle", toggle=True)
                distribution.prop(emission_props, "distribution_toggle", text="", icon='TRIA_DOWN'if emission_props.distribution_toggle else 'TRIA_LEFT')

                if emission_props.distribution_toggle:
                    fs_emission_emission.prop(emission_props, "use_modifier_stack", text="Use Modifier Stack")
                    fs_emission_emission.prop(emission_props, "show_unborn", text="Unborn")
                    fs_emission_emission.prop(emission_props, "use_emit_random", text="Random Order")
                    fs_emission_emission.prop(emission_props, "use_even_distribution", text="Even Distribution")
                
                # fs_emission_emission.separator()
                # unborn(fs_emission_emission, emission_props, emitter_ob)

                soft_start_end(col, toggles, active_group, emission_props)
    

    # Velocity:
    #----------

    # global_mode_velocity_sect
    velocity_local_mode = {
            "type": "bool",
            "from": switchers_props,
            "prop": "global_mode_velocity_sect",
            "text": "",
            "toggle": True,
            "icon": 'LINKED' if switchers_props.global_mode_velocity_sect else 'UNLINKED',
            "emboss": False,
    }
    fs_emission_velocity = collapsable(
        col,
        toggles,
        "fs_emission_velocity",
        "Velocity",
        'TIME',
        align=True,
        button_settings1=velocity_local_mode
    )
    if fs_emission_velocity:
        
        # Normal:
        fs_emission_velocity.prop(emission_props, "normal_factor", text="Normal")
        
        # Object velocity:
        fs_emission_velocity.prop(emission_props, "object_factor", slider=True, text="Object Velocity")

        fs_emission_velocity.separator()
        container = fs_emission_velocity.row(align=True)

        blocks = container.grid_flow(row_major=True, even_columns=False, even_rows=False, align=True, columns=2)

        left_block = blocks.column(align=True)

        left_block.alignment = 'RIGHT'

        left_block.label(text=" ")
        left_block.label(text="Initial Velocity ")

        right_block = blocks.column(align=True)
        right_block.scale_x = 0.52
                
        flow = right_block.grid_flow(row_major=True, even_columns=True, even_rows=True, align=True, columns=3)
        flow.scale_x = 2
        header_y_scale = 0.5

        head_x = flow.box().row(align=True) 
        head_x.alignment = 'CENTER'
        head_x.label(text="X")
        head_x.scale_y = header_y_scale

        head_y = flow.box().row(align=True) 
        head_y.alignment = 'CENTER'
        head_y.label(text="Y")
        head_y.scale_y = header_y_scale

        head_z = flow.box().row(align=True) 
        head_z.alignment = 'CENTER'
        head_z.label(text="Z")
        head_z.scale_y = header_y_scale

        axis_row = right_block.row(align=True)
        axis_row.prop(emission_props, "object_align_factor_x", text="")
        axis_row.prop(emission_props, "object_align_factor_y", text="")
        axis_row.prop(emission_props, "object_align_factor_z", text="")

    # Viewport Display:
    #------------------
    
    # global_mode_viewport_display_sect
    viewport_display_local_mode = {
            "type": "bool",
            "from": switchers_props,
            "prop": "global_mode_viewport_display_sect",
            "text": "",
            "toggle": True,
            "icon": 'LINKED' if switchers_props.global_mode_viewport_display_sect else 'UNLINKED',
            "emboss": False,
    }
    fs_emission_viewport_display = collapsable(
        col,
        toggles,
        "fs_emission_viewport_display",
        "Viewport Display",
        'RESTRICT_VIEW_OFF',
        align=True,
        button_settings1=viewport_display_local_mode
    )
    if fs_emission_viewport_display:
        
        disp_col = fs_emission_viewport_display.row(align=True)
        disp_col.scale_y = 1.3
        disp_col.prop(emission_props, "display_color", expand=True)

        if emission_props.display_color == 'MATERIAL':
            materials_detected = []

            # Si esta en modo Global muestro todos los colores de los materiales:
            if active_emitter_item.switchers.global_mode_viewport_display_sect:
                all_emitters = emitters_list.get_all_emitters
                for emitter_ob in all_emitters:
                    active_mat = emitter_ob.active_material
                    if active_mat:
                        fs_emission_viewport_display.prop(active_mat, "diffuse_color", text=emitter_ob.name + " Color")
                        materials_detected.append(active_mat)
            else:
                # Si está en local solo muestro el material del activo:
                active_mat = emitter_ob.active_material
                if active_mat:
                    fs_emission_viewport_display.prop(active_mat, "diffuse_color", text="Color")
                    materials_detected.append(active_mat)

            if len(materials_detected) <= 0:
                fs_emission_viewport_display.separator()
                fs_emission_viewport_display.box().label(text="No active material found!", icon='ERROR')

        fs_emission_viewport_display.separator(factor=0.5)